package com.sfeir.tv.client.mvc.framework;

public class Triad
{
    private Controller parent;
    private Model model;
    private View view;
    private Controller controller;
    private boolean destroyed;

    public Triad(final Controller parent, final Model model, final View view, final Controller controller)
    {
        this.parent = parent;
        this.model = model;
        this.view = view;
        this.controller = controller;
        init();
    }

    public Triad(final Model model, final View view, final Controller controller)
    {
        this(null, model, view, controller);
    }

    public Triad(final View view, final Controller controller)
    {
        this(null, new Model(), view, controller);
    }

    public Triad(final Controller parent, final View view)
    {
        this(parent, new Model(), view, new Controller());
    }

    public Triad(final Controller parent, final View view, final Controller controller)
    {
        this(parent, new Model(), view, controller);
    }

    private void init()
    {
        setParent();
        connectTriadParts();
        initParts();
    }

    private void setParent()
    {
        if( parent != null )
            setNonRootParent();
    }

    private void setNonRootParent()
    {
        parent.addChildController( controller );
        controller.setParent( parent );  // bi-directional: necessary?

//        putChildInMap();
    }

    private void putChildInMap()
    {
//        if (parent.getView() != null)
//            parent.getView().putChildInMap(view.getUniqueID(), view);
    }

    private void connectTriadParts()
    {
        controller.setModel( model );
        controller.setView( view );
        model.setController( controller );
        view.setController( controller );
        model.setView( view ); // ???
    }

    protected void initParts()
    {
        model.init();
        controller.init();
        view.init();
    }

    public Controller getController()
    {
        return controller;
    }

    public View getView()
    {
        return view;
    }

    public Model getModel()
    {
        return model;
    }

    public void destroy()
    {
        if (destroyed)
            return;
        Triad.destroyTriad(view, controller);
        destroyed = true;
    }

    public static void destroyTriad(final View view, final Controller controller)
    {
//        destroyChildTriads(controller);
//        view.dispose();
//        controller.dispose();
    }

    private static void destroyChildTriads(final Controller parent)
    {
//        for (int i = 0; i < parent.getChildrenCount(); i++)
//            destroyTriad(parent.getChildControllerAt(i).getView(),
//                         parent.getChildControllerAt(i));
    }
}
